import { useEffect, useState, useCallback } from 'react'

const useCountdown = (initial, callback) => {
  const [timing, setTiming] = useState(false)
  const [initialMinute, setInitialMinute] = useState(initial)
  const [second, setSecond] = useState(initialMinute * 60)

  useEffect(() => {
    let interval
    if (timing) {
      interval = setInterval(() => {
        setSecond(preSecond => {
          if (preSecond <= 1) {
            setTiming(false)
            clearInterval(interval)
            callback?.()
            return initialMinute * 60
          }
          return preSecond - 1
        })
      }, 1000)
    }
    return () => clearInterval(interval)
  }, [callback, initialMinute, timing])

  const onStart = useCallback(() => setTiming(true), [])
  const onStop = useCallback(() => setTiming(false), [])
  const resetMinute = useCallback(newInitialMinute => {
    setTiming(false)
    setInitialMinute(newInitialMinute)
    setSecond(newInitialMinute * 60)
    setTiming(true)
  }, [])

  return [second, timing, onStart, onStop, resetMinute]
}

export default useCountdown
